<template>
  <div class="skills-page">
    <!-- 标题区域 -->
    <div class="title-section">
      <h1 class="main-title">技能图鉴</h1>
      <p class="subtitle">探索各种强大的技能招式</p>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="输入编号或者技能名称"
          class="search-input"
          size="large"
          @keyup.enter="searchSkills"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button 
          type="primary" 
          size="large" 
          @click="searchSkills"
          class="search-btn"
        >
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button 
          @click="resetFilters" 
          size="large"
          class="reset-btn"
        >
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 技能表格 -->
     
    <div class="skills-table-container">
      <el-table 
        :data="displayedSkills" 
        style="width: 100%" 
        @row-click="selectSkill"
        class="skills-table"
        stripe
        border
      >
        <!-- 编号列 -->
        <el-table-column 
          prop="id" 
          label="编号" 
          width="80" 
          align="center"
          sortable
        />
        
        <!-- 中文名 -->
        <el-table-column 
          prop="moveName" 
          label="中文名" 
          width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div class="skill-name-cell">
              <span class="skill-name-text">{{ row.moveName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 学习方式 -->
        <el-table-column 
          label="学习方式" 
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <span class="learn-method">{{ getLearnMethodDisplay(row) }}</span>
          </template>
        </el-table-column>
        
        <!-- 属性 -->
        <el-table-column 
          prop="typeName" 
          label="属性" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span 
              class="type-badge table-badge"
              :class="`type-${row.typeName}`"
              :style="{ backgroundColor: row.typeColor }"
            >
              {{ row.typeName || '未知' }}
            </span>
          </template>
        </el-table-column>
        
        <!-- 分类 -->
        <el-table-column 
          prop="category" 
          label="分类" 
          width="80"
          align="center"
        >
          <template #default="{ row }">
            <span 
              class="category-badge table-badge"
              :class="row.category"
            >
              {{ getCategoryName(row.category) }}
            </span>
          </template>
        </el-table-column>
        
        <!-- 威力 -->
        <el-table-column 
          prop="power" 
          label="威力" 
          width="80"
          align="center"
          sortable
        >
          <template #default="{ row }">
            <span class="power-value">{{ row.power || '—' }}</span>
          </template>
        </el-table-column>
        
        <!-- 命中 -->
        <el-table-column 
          prop="accuracy" 
          label="命中" 
          width="80"
          align="center"
          sortable
        >
          <template #default="{ row }">
            <span class="accuracy-value">{{ row.accuracy || '—' }}</span>
          </template>
        </el-table-column>
        
        <!-- PP -->
        <el-table-column 
          prop="pp" 
          label="PP" 
          width="70"
          align="center"
          sortable
        >
          <template #default="{ row }">
            <span class="pp-value">{{ row.pp || '—' }}</span>
          </template>
        </el-table-column>
        
        <!-- 说明 -->
        <el-table-column 
          prop="description" 
          label="说明" 
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div class="description-cell">
              {{ row.description || '暂无描述' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页组件 -->
    <div v-if="!loading && total > 0" class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading && displayedSkills.length === 0" class="loading-state">
      <div class="loading-content">
        <div class="pokeball-loading">
          <div class="pokeball">
            <div class="pokeball-top"></div>
            <div class="pokeball-bottom"></div>
            <div class="pokeball-center"></div>
          </div>
        </div>
        <p>正在加载技能数据...</p>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="!loading && displayedSkills.length === 0" class="empty-state">
      <div class="empty-content">
        <div class="empty-icon">🔍</div>
        <h3>未找到相关技能</h3>
        <p>请尝试调整搜索条件</p>
        <el-button @click="resetFilters" type="primary" class="reset-primary-btn">重置搜索</el-button>
      </div>
    </div>
    
    <!-- 技能详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="selectedSkill?.moveName"
      width="600px"
      center
    >
      <div v-if="selectedSkill" class="skill-detail">
        <div class="detail-header">
          <div class="detail-meta">
            <span 
              class="type-badge large"
              :class="`type-${selectedSkill.typeName}`"
              :style="{ backgroundColor: selectedSkill.typeColor }"
            >
              {{ selectedSkill.typeName || '未知' }}
            </span>
            <span 
              class="category-badge large" 
              :class="selectedSkill.category"
            >
              {{ getCategoryName(selectedSkill.category) }}
            </span>
          </div>
        </div>
        
        <div class="detail-stats">
          <div class="stat-row">
            <div class="stat-item">
              <span class="stat-label">威力</span>
              <span class="stat-value">{{ selectedSkill.power || '-' }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">命中率</span>
              <span class="stat-value">{{ selectedSkill.accuracy || '-' }}%</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">PP</span>
              <span class="stat-value">{{ selectedSkill.pp || '-' }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-description">
          <h4>技能描述</h4>
          <p>{{ selectedSkill.description || '暂无描述' }}</p>
        </div>
        
        <div v-if="selectedSkill.effect" class="detail-effect">
          <h4>技能效果</h4>
          <p>{{ selectedSkill.effect }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getAllMoves, getMockMovesList, getMovesByPokemon, getMovesByName } from '@/api/moves.api.js'
// 移除了所有提示
import { Search } from '@element-plus/icons-vue'

// 响应式数据
const skillsList = ref([])
const allSkillsData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const selectedSkill = ref(null)

// 搜索
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

// 筛选后的技能列表（用于分页）
const filteredSkills = computed(() => {
  return skillsList.value
})

// 总数
const total = computed(() => {
  return filteredSkills.value.length
})

// 显示的技能列表（经过分页的）
const displayedSkills = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredSkills.value.slice(start, end)
})

// 根据技能信息推断分类
const inferCategory = (skill) => {
  if (!skill.power || skill.power === 0) {
    return 'status' // 无威力的技能通常是变化技能
  }
  
  // 根据属性和威力推断物理/特殊
  // 一般来说：格斗、岩石、地面、飞行、虫、幽灵、钢 倾向于物理
  // 火、水、电、草、冰、超能力、龙 倾向于特殊
  const physicalTypes = ['格斗', '岩石', '地面', '飞行', '虫', '钢']
  const specialTypes = ['火', '水', '电', '草', '冰', '超能力', '龙']
  
  if (physicalTypes.includes(skill.typeName)) {
    return 'physical'
  } else if (specialTypes.includes(skill.typeName)) {
    return 'special'
  }
  
  // 默认根据威力判断（这是一个简化的规则）
  return skill.power >= 60 ? 'physical' : 'special'
}

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    'physical': '物理',
    'special': '特殊', 
    'status': '变化'
  }
  return categoryMap[category] || '未知'
}

// 获取学习方式显示文本
const getLearnMethodDisplay = (skill) => {
  // 如果有具体的学习方式数据，优先使用
  if (skill.learnMethod && skill.learnLevel !== undefined) {
    if (skill.learnMethod === 'level') {
      return skill.learnLevel === 0 ? '初始技能' : `lv.${skill.learnLevel}`
    } else if (skill.learnMethod === 'tm' || skill.learnMethod === 'machine') {
      return '学习器'
    }
  }
  
  // 根据技能ID推断学习方式（简化逻辑）
  // 这里使用一些启发式规则来推断学习方式
  if (skill.id <= 50) {
    // 前50个技能大多是基础技能，可能是等级学习
    const level = Math.floor(skill.id / 5) * 5 + 5 // 简单的等级计算
    return level <= 5 ? '初始技能' : `lv.${level}`
  } else if (skill.id > 100) {
    // 高编号技能可能是学习器技能
    return '学习器'
  } else {
    // 中等编号技能，随机分配等级
    const level = Math.floor(skill.id / 10) * 5
    return level <= 5 ? '初始技能' : `lv.${level}`
  }
}



// 获取技能列表
const fetchSkillsList = async () => {
  try {
    loading.value = true
    
    let response
    try {
      response = await getAllMoves()
    } catch (error) {
      response = await getMockMovesList()
    }
    
    if (response) {
      let skillsData = Array.isArray(response) ? response : (response.data || [])
      
      // 为每个技能推断分类（如果后端没有提供的话）
      skillsData = skillsData.map(skill => ({
        ...skill,
        category: skill.category || inferCategory(skill)
      }))
      
      skillsList.value = skillsData
      allSkillsData.value = skillsData
    } else {
      // 获取技能列表失败
    }
  } catch (error) {
    // 网络错误
  } finally {
    loading.value = false
  }
}

// 搜索技能
const searchSkills = async () => {
  const keyword = searchKeyword.value.trim()
  
  if (!keyword) {
    // 如果没有搜索关键词，显示所有技能
    skillsList.value = [...allSkillsData.value]
    return
  }
  
  try {
    loading.value = true
    let searchResults = []
    
    // 判断是否为数字（技能编号）
    if (/^\d+$/.test(keyword)) {
      const skillId = parseInt(keyword)
      // 按编号搜索
      searchResults = allSkillsData.value.filter(skill => skill.id === skillId)
      // 搜索技能ID完成
    } else {
      // 先尝试按技能名称搜索
      const lowerKeyword = keyword.toLowerCase()
      searchResults = allSkillsData.value.filter(skill => 
        skill.moveName?.toLowerCase().includes(lowerKeyword) ||
        skill.skillName?.toLowerCase().includes(lowerKeyword)
      )
      
      // 如果按技能名称没找到，尝试按宝可梦名称搜索
      if (searchResults.length === 0) {
        try {
          const response = await getMovesByPokemon(keyword)
          
          if (response && Array.isArray(response) && response.length > 0) {
            // 直接使用API返回的技能数据
            searchResults = response.map(skill => ({
              ...skill,
              category: skill.category || inferCategory(skill)
            }))
            // 找到宝可梦技能
          } else if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
            // 如果数据在response.data中
            searchResults = response.data.map(skill => ({
              ...skill,
              category: skill.category || inferCategory(skill)
            }))
            // 找到宝可梦技能
          } else {
            // 未找到相关技能或宝可梦
          }
        } catch (error) {
          // 未找到相关技能
        }
      } else {
        // 找到匹配的技能
      }
    }
    
    skillsList.value = searchResults
    currentPage.value = 1 // 搜索后重置到第一页
  } catch (error) {
    // 搜索失败
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetFilters = () => {
  searchKeyword.value = ''
  skillsList.value = [...allSkillsData.value]
  currentPage.value = 1 // 重置到第一页
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

// 选择技能
const selectSkill = (skill) => {
  selectedSkill.value = skill
  dialogVisible.value = true
}

// 页面挂载时获取数据
onMounted(() => {
  fetchSkillsList()
})
</script>

<style scoped>
.skills-page {
  padding: 40px 20px;
}

/* 标题区域 */
.title-section {
  text-align: center;
  margin-bottom: 50px;
}

.main-title {
  font-size: 3.5rem;
  font-weight: bold;
  color: #2c5aa0;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  animation: fadeInUp 1s ease-out;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  margin: 10px 0 0 0;
  animation: fadeInUp 1s ease-out 0.2s both;
}

/* 搜索区域 */
.search-section {
  max-width: 1200px;
  margin: 0 auto 40px auto;
  padding: 0;
}

.search-bar {
  display: flex;
  gap: 15px;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  max-width: 400px;
  min-width: 250px;
}

.search-btn {
  min-width: 120px;
  border-radius: 25px;
  font-weight: 600;
  background-color: #1890ff !important;
  border-color: #1890ff !important;
}

.search-btn:hover {
  background-color: #096dd9 !important;
  border-color: #096dd9 !important;
}

.reset-btn {
  min-width: 80px;
  border-radius: 25px;
  font-weight: 600;
  margin-left: 10px;
  color: white !important;
}

.reset-primary-btn {
  color: white !important;
}

.filters {
  display: flex;
  gap: 15px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.filters .el-select {
  min-width: 150px;
}

/* 技能表格容器 */
.skills-table-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
  background: transparent;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.skills-table {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-header-text-color: #303133;
  --el-table-row-hover-bg-color: #f0f9ff;
}

.skills-table .el-table__header-wrapper {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.skills-table .el-table__header th {
  background: transparent !important;
  color: white !important;
  font-weight: 600;
  padding: 12px 0;
  border-bottom: none;
  text-align: center;
}

.skills-table .el-table__row {
  cursor: pointer;
  transition: all 0.2s ease;
}

.skills-table .el-table__row:hover {
  background-color: #f0f9ff !important;
}

.skills-table .el-table__row td {
  padding: 10px 0;
  vertical-align: middle;
}

/* 表格单元格样式 */
.skill-name-cell {
  font-weight: 600;
  color: #303133;
}

.skill-name-text {
  font-size: 14px;
}

.table-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-align: center;
  min-width: 40px;
}

.move-id {
  font-weight: 600;
  color: #606266;
  font-size: 13px;
}

.learn-method {
  font-size: 12px;
  font-weight: 500;
  color: #67c23a;
  background-color: #f0f9ff;
  padding: 2px 6px;
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

.power-value, .accuracy-value, .pp-value {
  font-weight: 600;
  color: #409eff;
}

.description-cell {
  font-size: 13px;
  line-height: 1.4;
  color: #606266;
  max-width: 300px;
}

.skill-header {
  margin-bottom: 15px;
}

.skill-name {
  font-size: 1.3rem;
  font-weight: bold;
  color: #333;
  margin: 0 0 10px 0;
}

.skill-meta {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.type-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
}

.type-badge.large {
  padding: 6px 16px;
  font-size: 0.9rem;
}

.category-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
  color: white;
}

.learn-method-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-align: center;
  min-width: 50px;
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.learn-method-level {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.learn-method-tm {
  background: linear-gradient(135deg, #fa709a, #fee140);
}

.category-badge.large {
  padding: 6px 16px;
  font-size: 0.9rem;
}

.category-badge.physical {
  background: #e74c3c;
}

.category-badge.special {
  background: #3498db;
}

.category-badge.status {
  background: #95a5a6;
}

/* 技能统计 */
.skill-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-label {
  display: block;
  font-size: 0.85rem;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.skill-description {
  color: #666;
  line-height: 1.5;
  font-size: 0.95rem;
}

/* 属性类型颜色 */
.type-草 { background: #7AC74C; }
.type-火 { background: #EE8130; }
.type-水 { background: #6390F0; }
.type-电 { background: #F7D02C; color: #333; }
.type-超能力 { background: #F95587; }
.type-冰 { background: #96D9D6; }
.type-龙 { background: #6F35FC; }
.type-恶 { background: #705746; }
.type-妖精 { background: #D685AD; }
.type-格斗 { background: #C22E28; }
.type-毒 { background: #A33EA1; }
.type-地面 { background: #E2BF65; }
.type-飞行 { background: #A98FF3; }
.type-虫 { background: #A6B91A; }
.type-岩石 { background: #B6A136; }
.type-幽灵 { background: #735797; }
.type-钢 { background: #B7B7CE; }
.type-一般 { background: #A8A878; }

/* 详情弹窗 */
.skill-detail {
  padding: 10px 0;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-meta {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.detail-stats {
  margin-bottom: 25px;
}

.stat-row {
  display: flex;
  justify-content: space-around;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 10px;
}

.detail-description,
.detail-effect {
  margin-bottom: 20px;
}

.detail-description h4,
.detail-effect h4 {
  color: #2c5aa0;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.detail-description p,
.detail-effect p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 100px 0;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-content {
  color: #666;
}

.loading-content p {
  margin-top: 20px;
  font-size: 1.1rem;
}

/* 精灵球加载动画 */
.pokeball-loading {
  display: inline-block;
}

.pokeball {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  position: relative;
  animation: pokeball-spin 2s linear infinite;
}

.pokeball-top {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 50%;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  border-radius: 60px 60px 0 0;
  border: 3px solid #333;
  border-bottom: 2px solid #333;
}

.pokeball-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50%;
  background: linear-gradient(135deg, #ffffff, #f8f9fa);
  border-radius: 0 0 60px 60px;
  border: 3px solid #333;
  border-top: 2px solid #333;
}

.pokeball-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background: #ffffff;
  border: 4px solid #333;
  border-radius: 50%;
  z-index: 10;
}

.pokeball-center::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 8px;
  background: #333;
  border-radius: 50%;
}

@keyframes pokeball-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 30px 0;
  padding: 20px 0;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100px 0;
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-content {
  color: #999;
  max-width: 400px;
}

.empty-content h3 {
  color: #666;
  font-size: 1.5rem;
  margin: 20px 0 10px 0;
}

.empty-content p {
  color: #999;
  font-size: 1rem;
  line-height: 1.6;
  margin-bottom: 30px;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
  opacity: 0.5;
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-title {
    font-size: 2.5rem;
  }
  
  .skills-table-container {
    margin: 0 10px;
    padding: 0 10px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    max-width: none;
  }
  
  .filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filters .el-select {
    min-width: auto;
  }
  
  .skills-table .el-table__header th {
    padding: 8px 0;
    font-size: 12px;
  }
  
  .skills-table .el-table__row td {
    padding: 8px 0;
  }
  
  .table-badge {
    font-size: 10px;
    padding: 1px 6px;
  }
}

@media (max-width: 480px) {
  .main-title {
    font-size: 2rem;
  }
  
  .skills-page {
    padding: 20px 10px;
  }
}
</style>